const {app} = require('electron');
const PicGo = require('picgo');
const fs = require('fs');
const Path = require('path');
const OS = require('os');
const DataStore = require('../../app-store')
const dataStore = new DataStore()
const dt = require('silly-datetime')
const configPath = Path.join(OS.homedir(), app.name, 'picgo.json');

function initConfigFile() {
    if (!fs.existsSync(configPath)){
        if (!fs.existsSync(Path.dirname(configPath))) {
            fs.mkdirSync(Path.dirname(configPath))
        }
        fs.writeFileSync(configPath, fs.readFileSync(Path.join(__dirname, Path.basename(configPath))))
    }
}

function uploadPicture(filepath, name) {
    return new Promise((resolve, reject) => {
        initConfigFile();
        const picgo = new PicGo(configPath);
        // 切换
        picgo.setConfig({
            'picBed.uploader': name
        });
        const uploadPath = dt.format(new Date(),'YYYYMMDD')
        if( filepath.hasOwnProperty('imageRealPath') ){
            picgo.setConfig({'picBed.gitee.path':"/images/"+uploadPath+"/"+filepath.uuid});
            picgo.upload([filepath.imageRealPath]);
        } else {
            // 上传
            picgo.setConfig({'picBed.gitee.path':"/images/"+uploadPath});
            picgo.upload([filepath]);
        }
        // 如果图片
        picgo.on("notification",function(result){
            if( result.body.search("already exists")!=-1 ){
                resolve(result.url);
            }
            if( result.body.search("更新失败")!=-1 ){
                uploadPicture(filepath, name)
                    .then(r=>{
                        resolve(result.url)
                    })
                    .catch(m=>{
                        reject(m)
                    })
            }else{
                reject(result.body)
            }
        });
        // 监听结果
        picgo.on('finished', ctx => {
            if (ctx.output.length>0 && ctx.output[0].imgUrl) {
                resolve(ctx.output[0].imgUrl)
                // [{fileName, width, height, extname, imgUrl}]
            }
            // deleteLog()
        });
        // 监听错误
        picgo.on('failed', error => {
            reject(error);
            // deleteLog()
        })
    })
}

function deleteLog(){
    setTimeout(function () {
        const packageFile = Path.join(Path.dirname(configPath), 'package.json');
        if (fs.existsSync(packageFile)) {
            fs.unlinkSync(packageFile)
        }
    }, 1000)
}

exports.configPath = configPath;
exports.initConfigFile = initConfigFile;
exports.uploadPicture = uploadPicture;
